import time,pytesseract
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from PIL import Image


class GuShiWang():

    # 初始化
    def __init__(self):
        self.url = 'https://so.gushiwen.cn'
        self.driver = webdriver.Chrome('chromedriver.exe')
        self.driver.get(self.url)

    # 首页截图
    def Index(self):
        driver = self.driver
        for i in range(1, 4):
            time.sleep(1)
            driver.get_screenshot_as_file('img/text{}.png'.format(i))
            print('正在截取第%s图' % i)
            driver.execute_script('window.scrollTo(0,{})'.format(i * 200))

    # 登录
    def Login(self):
        driver = self.driver

        # 找到登录页
        time.sleep(1)
        driver.find_element(By.LINK_TEXT, '我的').click()

        # 输入账号
        time.sleep(1)
        driver.find_element(By.ID, 'email').send_keys('17642189420')

        # 输入密码
        time.sleep(1)
        driver.find_element(By.ID, 'pwd').send_keys('mfx123456')

        # 输入验证码
        # driver.get_screenshot_as_file(r'img/image_code.jpg')
        driver.find_element(By.ID, 'code').send_keys(input('请输入：'))
        # su = driver.find_element(By.ID, 'code')
        # print(su.location)
        # left = su.location['x'] + int(165)
        # top = su.location['y'] + int(55)
        # right = su.size['width'] + left + int(20)
        # height = su.size['height'] + top
        # # 点击回车
        # im = Image.open(r"img/image_code.jpg")
        #
        # img = im.crop((left, top, right, height))
        # img.save(r"img/image_code1.png")
        #
        # img_text = Image.open('img/image_code1.png')
        # text = pytesseract.image_to_string(img_text)
        #
        # print(text)

        time.sleep(3)
        button_login = driver.find_element(By.ID, 'denglu')
        button_login.send_keys(Keys.ENTER)

    # 搜索+滑动
    def Search(self):
        driver = self.driver
        # 搜索点击
        time.sleep(3)
        button_serch = driver.find_element(By.ID, 'txtKey')
        button_serch.send_keys(input('请输入：'))
        time.sleep(2)
        button_serch.send_keys(Keys.ENTER)

        # 向下滑动
        time.sleep(2)
        driver.execute_script('window.scrollTo(0,500)')

    # 收藏+查看收藏
    def Add_Search_list(self):
        driver = self.driver
        # 点击收藏
        time.sleep(2)
        driver.find_element(By.ID, 'likeImg64945').click()

        # 点击我的
        time.sleep(3)
        driver.find_element(By.LINK_TEXT, '我的').click()

        time.sleep(6)
        driver.quit()


if __name__ == '__main__':
    gushiwang = GuShiWang()
    gushiwang.Index()
    gushiwang.Login()
    gushiwang.Search()
    gushiwang.Add_Search_list()
